<?php

/**
 * description...
 *
 * @author Tinyhu
 * @package AdminController
 */
class CustomerController extends Controller
{
    public $layout = 'admin';
    private $top = null;
    public $needRightActions = array('*' => true);

    public function init()
    {
        $menu = new Menu();
        $this->assign('mainMenu', $menu->getMenu());
        $menu_index = $menu->current_menu();
        $this->assign('menu_index', $menu_index);
        $this->assign('subMenu', $menu->getSubMenu($menu_index['menu']));
        $this->assign('menu', $menu);
        $nav_act = Req::get('act') == null ? $this->defaultAction : Req::get('act');
        $nav_act = preg_replace("/(_edit)$/", "_list", $nav_act);
        $this->assign('nav_link', '/' . Req::get('con') . '/' . $nav_act);
        $this->assign('node_index', $menu->currentNode());
        $this->safebox = Safebox::getInstance();
        $this->assign('manager', $this->safebox->get('manager'));

        $currentNode = $menu->currentNode();
        if (isset($currentNode['name'])) $this->assign('admin_title', $currentNode['name']);
    }

    public function noRight()
    {
        $this->redirect("admin/noright");
    }

    //审核开通创客
    public function ck_ok()
    {
        $id = Req::args("id");
        $ck_money = Common::getConfigJjsetValue("jjset_ck_chongzhi");
        $model = new Model("customer");
        $money = $model->fields("balance,user_id")->where("user_id=" . $id)->find()['balance'];
        if ($money < $ck_money) {
            $this->msg = array("warning", "账户余额不足，无法开通创客！");
        } else {
            $model->data(array('ck_ok' => 2, 'balance' => "`balance`-$ck_money"))->where("user_id=" . $id)->update();
            $model->table("user")->data(array('u_lx' => 1))->where("id=" . $id)->update();
            $this->msg = array("success", "操作成功！");
        }
        $this->redirect("customer_list", false);

    }

    public function test1()
    {
        $result = Common::get_sons_tjrs(5,10);

        var_dump($result);
    }
    public function test()
    {
        $model = new Model();
        $i = 1;
        $childs_id = [];
//		$childs = $model->table('users')->where('pid',$user->id)->get();//子一代对象
        $chils = $model->query("select id from zyk_user where tjr_id=5");//子一代对象
        $childs = [];
        foreach ($chils as $chil) {
            $childs[] = $chil['id'];
        }
//		print_r($childs);die;

        $array = Common::get_son_user($childs,$childs_id,$model,$i=1);


        var_dump($array);
    }


    public function set_seller()
    {
        $id = intval(Req::args('id'));
        $model = new Model();
        $result = $model->table("user")->data(['is_seller' => 1])->where("id=" . $id)->update();
        if ($result) {
            $model->query("insert into zyk_seller(seller_id) select $id");
            $msg = array("success", "操作成功");
        } else {
            $msg = array("error", "操作失败");
        }
        $url = Url::getRefRoute();
        $this->redirect($url, true, array('msg' => $msg));
    }

    public function set_u_lx()
    {
        $id = intval(Req::args('id'));
        $lx = intval(Req::args("lx"));
        if ($id > 0 && $lx > 0) {
            $model = new Model();
            //设为服务中心、分公司的同时也就是合格会员了
            $result = $model->table("user")->data(['u_lx' => $lx, 'is_hg' => 1])->where("id=" . $id)->update();
            if ($result) {
                $msg = array("success", "操作成功");
            } else {
                $msg = array("error", "操作失败");
            }

        } else {
            $msg = array("error", "操作失败");
        }
        $url = Url::getRefRoute();
        $this->redirect($url, true, array('msg' => $msg));
    }

    public function unset_u_lx()
    {
        $id = intval(Req::args('id'));
        //$lx = intval(Req::args("lx"));
        if ($id > 0) {
            $model = new Model();
            $result = $model->table("user")->data(['u_lx' => 0])->where("id=" . $id)->update();
            if ($result) {
                $msg = array("success", "操作成功");
            } else {
                $msg = array("error", "操作失败");
            }
        } else {
            $msg = array("error", "操作失败");
        }
        $url = Url::getRefRoute();
        $this->redirect($url, true, array('msg' => $msg));
    }


    /**
     * 保存充值扣款记录
     * @param unknown $arr
     */
    static function save_recharge_info($arr)
    {
        $model = new Model();
        $model->table("recharge")->data($arr)->insert();
    }


    //充值与退款
    public function balance_op()
    {
        $user_id = Filter::int(Req::args('user_id'));//用户id
        $type = Filter::int(Req::args('type'));//2充值 4扣款
        $amount = Filter::float(Req::args('amount'));//金额
        $account_type = intval(Req::args('account_type'));//账户类型
        //事件类型: 1:注册分 2:奖金分 3：现金分 4:购物积分 5:重消积分  6:资产  7:剩余分红

        $demo_account_type = Common::get_account_zd($account_type);//账户对应字段(改)
        $account_name = Common::get_account_name($account_type); //账户类型名字(改)

        $model = new Model("customer");

        $obj = $model->where("user_id=$user_id")->find();

        $info = array('status' => 'fail');

        $demo_ye = $obj[$demo_account_type];//临时账户余额
        $range = 1000000000 - $demo_ye;
        //		$range = 1000000000-$obj['balance'];
        if ($obj && $amount > 0 && $amount <= $range) {

            $manager_name = $this->manager['name'];

            $data['user_id'] = $user_id;
            $data['je'] = $amount;
            $data['account_type'] = $account_type;
            $data['admin'] = $manager_name;

            if ($type == 2)//充值
            {
                //$model->data(array('balance'=>"`balance`+".$amount))->where("user_id=$user_id")->update();
                $model->data(array($demo_account_type => "`$demo_account_type`+" . $amount))->where("user_id=$user_id")->update();

                $data['type'] = 0;//表面是充值
                self::save_recharge_info($data);

                //保存日志信息
                Log::balance($amount, $user_id, '管理员' . $manager_name . '为您充值,' . $account_name . ',充值的金额为：' . $amount, 2, $this->manager['id']);

                $info = array('status' => 'success', 'msg' => '充值成功。');
            } else if ($type == 4)//扣款
            {
                if ($amount > $demo_ye) {
                    $info = array('status' => 'fail', 'msg' => '账户余额不足');
                } else {
                    //$model->data(array('balance'=>"`balance`-".$amount))->where("user_id=$user_id")->update();
                    $model->data(array($demo_account_type => "`$demo_account_type`-" . $amount))->where("user_id=$user_id")->update();

                    $data['type'] = 1;//表面是扣款
                    self::save_recharge_info($data);

                    Log::balance($amount, $user_id, '管理员' . $manager_name . '从您的' . $account_name . '余额中扣款,扣款金额为：' . $amount, 4, $this->manager['id']);
                    $info = array('status' => 'success', 'msg' => '操作成功。');
                }
            }
        } else {
            $info = array('status' => 'fail', 'msg' => '此用户可充值的金额范围0.01-' . sprintf("%01.2f", $range));
        }
        echo JSON::encode($info);
    }

    /**
     * 充值扣款列表
     */
    public function recharge_list()
    {
        //$arr = ['','账户余额','消费积分(冻结)','消费积分(可用)','云积分','推广额度(总额)','通用积分','消费券'];
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);

        $model = new Model();

        //总充值金额
        $list1 = $model->query("select sum(je) as total from zyk_recharge where type=0");
        $total_1 = $list1[0]['total'];

        //总扣款金额
        $list2 = $model->query("select sum(je) as total from zyk_recharge where type=1");
        $total_2 = $list2[0]['total'];

// 	    //账户余额总充值
// 	    $list2 = $model->query("select sum(je) as total from zyk_recharge where type=0 and account_type=1");
// 	    $total_2 = $list2[0]['total'];

// 	    //账户余额总扣款
// 	    $list2 = $model->query("select sum(je) as total from zyk_recharge where type=1 and account_type=1");
// 	    $total_2 = $list2[0]['total'];

// 	    $list2 = $model->query("select sum(je) as total from zyk_recharge where type=1");
// 	    $total_2 = $list2[0]['total'];

// 	    $list2 = $model->query("select sum(je) as total from zyk_recharge where type=1");
// 	    $total_2 = $list2[0]['total'];

        $this->assign('total_1', $total_1);
        $this->assign('total_2', $total_2);
        $this->redirect();
    }

    /**
     * 激活记录
     */
    public function active_list()
    {

        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    /**
     * 复投记录
     */
    public function ft_list()
    {

        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }


    public function balance_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    public function fan_info_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    public function fan_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    public function kou_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    public function withdraw_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);

        $model = new Model();
        //总提现金额
        $list1 = $model->query("select sum(sq_money) as total from zyk_withdraw");
        $total_1 = floatval($list1[0]['total']);

        //待处理
        $list2 = $model->query("select sum(sq_money) as total from zyk_withdraw where status=0");
        $total_2 = floatval($list2[0]['total']);

        //已同意
        $list3 = $model->query("select sum(sq_money) as total from zyk_withdraw where status=1");
        $total_3 = floatval($list3[0]['total']);

        //已拒绝
        $list4 = $model->query("select sum(sq_money) as total from zyk_withdraw where status=2");
        $total_4 = floatval($list4[0]['total']);

        $this->assign("total_1", $total_1);
        $this->assign("total_2", $total_2);
        $this->assign("total_3", $total_3);
        $this->assign("total_4", $total_4);
        $this->redirect();
    }

    //冻结会员
    public function customer_nojj()
    {

        $id = Req::args("id");
        $model = new Model("user");
        $nojj = $model->where("id=" . $id)->find()['nojj'];
        if ($nojj == 1) {
            $zt = 0;
        } else $zt = 1;
        $model->data(array('nojj' => $zt))->where("id=" . $id)->update();
        $this->redirect("customer_list");
    }

    //锁定会员
    public function customer_clock()
    {
        $id = Req::args("id");
        // $lx = Req::args("lx");
        $model = new Model();
        $isclock = $model->table("user")->where("id=" . $id)->find()['status'];
        if ($isclock == 1) {
            $zt = 2;
        } else $zt = 1;
        $model->table("user")->data(array('status' => $zt))->where("id=" . $id)->update();
        $this->redirect("customer_list");
    }

    //开通社区
    public function lgd_ok()
    {
        $id = Req::args("id");
        $model = new Model("user");
        $model->data(array('lgd_ok' => 3))->where("id=" . $id)->update();
        //Jjjs::tjj_ckordp($id,3);//计算奖金
        $this->redirect("customer_list");
    }

    //设为股东
    public function gd_ok()
    {
        $id = Req::args("id");
        $model = new Model("user");
        $model->data(array('gd_ok' => 4))->where("id=" . $id)->update();
        $this->redirect("customer_list");
    }

    //设为注册默认推荐人
    public function tjr_ok()
    {
        $id = Req::args("id");
        $model = new Model();
        $isclock = $model->table("user")->where("id=" . $id)->find()['tjr_index'];
        if ($isclock == 0) {
            $zt = 1;
        } else $zt = 0;
        $model->table("user")->data(array('tjr_index' => $zt))->where("id=" . $id)->update();
        $this->redirect("customer_list");
    }

    public function seller_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    public function sq_list()
    {

        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    public function sq_do()
    {
        $model = new Model();
        $sq_id = intval(Req::args('sq_id'));
        $is_ok = intval(Req::args("is_ok"));
        $sq_obj = $model->table("sq_list")->where("sq_id=$sq_id")->find();
        if (!empty($sq_obj) && intval($sq_obj['is_ok']) === 0) {
            $now_time = date('Y-m-d H:i:s');
            $sh_user = $this->manager['name'];
            $result = $model->table("sq_list")->data(['is_ok' => $is_ok, 'sh_time' => $now_time, 'sh_user' => $sh_user])->where("sq_id=$sq_id")->update();
            if ($is_ok === 1)//通过
            {
                $user_id = $sq_obj['user_id'];
                $data = ['u_lx' => $sq_obj['sq_lx']];
                $result2 = $model->table("user")->data($data)->where("id=" . $user_id)->update();
            }
            if ($result) {
                $msg = array("success", "操作成功");
            } else {
                $msg = array("error", "操作失败");
            }
        } else {
            $msg = array("error", "操作失败");
        }

        $url = Url::getRefRoute();
        $this->redirect($url, true, array('msg' => $msg));
    }

    public function seller_dp_edit()
    {
        $id = Req::args("id");

        $model = new Model();

        $dp_info = $model->table("dp")->where("user_id =" . $id)->find(); //获取店铺信息
        $this->assign("id", $id);
        $this->assign("dp_info", $dp_info);
        $this->redirect();
    }


    //查看申请店铺
    public function dp_view()
    {
        $this->layout = "blank";
        $id = Filter::int(Req::args('id'));
        if ($id) {
            $model = new Model('dp');
            //$dp = $model->fields("wd.*,sq.*")->join("left join sq_list as sq on wd.user_id = sq.user_id")->where("sq.sq_id=$id")->find();
            //$dp = $model->table("dp")->where("did=$id")->find();
            $dp = $model->table("dp")->where("user_id =" . $id)->find();
//			$this->assign("dp",$dp);
            $this->assign("id", $id);
            $this->redirect();
        }
    }

    public function customer_dp_edit()
    {
        $id = Req::args("id");
        $dp_name = Req::args("dp_name");
        $dp_tel = Req::args("dp_tel");

        $upfile_path = Tiny::getPath("uploads");
        $upfile_url = preg_replace("|^" . APP_URL . "|", '', Tiny::getPath("uploads_url"));
        $upfile = new UploadFile('dp_logo', $upfile_path, '10m');
        $upfile->save();
        $info = $upfile->getInfo();

        if ($info[0]['status'] == 1) {
            $url = $upfile_url . $info[0]['path'];

        }


        $dp_logo = $url;  //获取图片路径

        if (empty($dp_logo)) {
            $data = array(
                "dp_name" => $dp_name,
                "dp_tel" => $dp_tel,
                "sh_time" => date("Y-m-d H:i:s")   //修改店铺的时间
            );
        } else {
            ////判断用户上传文件格式是否合法
            $imgPath = $info[0]['path'];
            if ($imgPath == null) {  //跳转到上传图片的页面
                $msg = array("error", "操作失败");
                $url_tz = Url::getRefRoute();
                $this->redirect($url_tz, true, array('msg' => $msg));
            }

            $data = array(
                "dp_name" => $dp_name,
                "dp_tel" => $dp_tel,
                "sh_time" => date("Y-m-d H:i:s"),
                "dp_logo" => $dp_logo
            );

        }
        $model = new Model();

        $dp_name_rep = $model->table("dp")->data($data)->where("user_id =" . $id)->update(); //检查

        if ($dp_name_rep) {

            $msg = array("success", "操作成功");
            $url = Url::getRefRoute();
            $this->redirect($url, true, array('msg' => $msg));
            echo "<script>parent.close();</script>";
        }

    }


    /**
     * 设置为商家时店铺名称检查
     */
    public function dp_name_ref()
    {
        $dp_name = $_GET['dp_name'];//echo $dp_name;

        if (empty($dp_name)) {

            $message = "error1";
            echo json_encode($message);
            die;
        }
        $model = new Model();
        $dp_name_rep = $model->table("dp")->where("dp_name = '{$dp_name}'")->find(); //检查

        if ($dp_name_rep) {
            $message = "error2";
            echo json_encode($message);
            die;
        }

    }

    //审核店铺
    public function dp_act()
    {
        $user_id = Filter::int(Req::args('user_id'));  //用户的id
        $dp_name = Req::args('dp_name');  //用户的id

        $dp_tel = Filter::int(Req::args('dp_tel'));  //店铺的电话
        $upfile_path = Tiny::getPath("uploads");
        $upfile_url = preg_replace("|^" . APP_URL . "|", '', Tiny::getPath("uploads_url"));
        $upfile = new UploadFile('dp_logo', $upfile_path, '10m');
        $upfile->save();
        $info = $upfile->getInfo();

        if ($info[0]['status'] == 1) {
            $url = $upfile_url . $info[0]['path'];

        }

        ////判断用户上传文件格式是否合法
        $imgPath = $info[0]['path'];
        if ($imgPath == null) {  //跳转到上传图片的页面
            $msg = array("error", "操作失败");
            $url = Url::getRefRoute();
            $this->redirect($url, true, array('msg' => $msg));
        }
        $dp_logo = $url;  //获取图片路径

        $model = new Model();

        $dp_name_rep = $model->table("dp")->where("dp_name =" . "$dp_name")->find(); //检查

        if ($dp_name_rep) {
            $msg = array("error", "操作失败");
            $url = Url::getRefRoute();
            $this->redirect($url, true, array('msg' => $msg));
        }


        $user_update = $model->table("user")->where("id =" . $user_id)->data(array("is_seller" => "1"))->update();
        $data = array(
            'user_id' => $user_id,
            "dp_name" => "$dp_name",
            "dp_tel" => "$dp_tel",
            "dp_logo" => "$dp_logo",
            "sq_time" => date("Y-m-d, H:i:s", time())  //通过时间
        );
        $dp_insert = $model->table("dp")->data($data)->insert();

        $seller_data = array(
            "seller_id" => $user_id,
            "create_time" => date("Y-m-d H:i:s", time())
        );

        $seller_insert = $model->table("seller")->data($seller_data)->insert();

        if ($user_update && $dp_insert && $seller_insert) {
            echo "<script>parent.close();</script>";
        }

//		$sq_id = Filter::int(Req::args('sq_id'));
        $dp_id = Filter::int(Req::args('user_id'));
        // $status = intval(Req::args('status'));
        // $re_note = Filter::text(Req::args('re_note'));

//		$model = new Model('dp');
//		$model->data(array('is_ok'=>2,'sh_time'=>date('Y-m-d H:i:s')))->where("user_id=$dp_id")->update();
//		$model->table('sq_list')->data(array('is_ok'=>1))->where("sq_id=$sq_id")->update();
//		$model->table('user')->data(array('u_lx'=>2,'is_seller'=>1))->where("id=$dp_id")->update();
//		//Jjjs::tjj_ckordp($dp_id,2);//计算奖金
//		echo "<script>parent.close_dialog();</script>";
    }

    function photoshop_upload()
    {
        $file = $_FILES['upfile'];
        if ($file['error'] == 4) {
            $msg = array('error', '请选择文件后再上传！');
            $this->redirect("photoshop", true, array('msg' => $msg));
        } else if ($file['error'] == 1) {
            $msg = array('error', '文件超出了php.ini文件指定大小！');
            $this->redirect("photoshop", true, array('msg' => $msg));
        } else if ($file['size'] > 0) {
            $key = md5_file($file['tmp_name']);
            $gallery = new Model('gallery');
            $img = $gallery->where("`key`='" . $key . "'")->find();
            echo JS::import('dialog?skin=brief');
            echo JS::import('dialogtools');
            if (!$img) {
                $upfile_path = Tiny::getPath("uploads");
                $upfile_url = preg_replace("|^" . APP_URL . "|", '', Tiny::getPath("uploads_url"));
                $upfile = new UploadFile('upfile', $upfile_path, '10m');
                $upfile->save();
                $info = $upfile->getInfo();
                $result = array();
                if ($info[0]['status'] == 1) {
                    $url = $upfile_url . $info[0]['path'];
                    $key = md5_file($upfile_path . $info[0]['path']);
                    $type = Req::args("type") == null ? 0 : intval(Req::args('type'));
                    $gallery->data(array('key' => $key, 'type' => $type, 'img' => $url))->save();
                    echo("<script>art.dialog.opener.setImg('$url');</script>");
                } else {
                    $msg = array('error', $info[0]['msg']);
                    $this->msg = $msg;
                    $this->redirect("photoshop", false);
                }
            } else {
                $url = $img['img'];
                echo("<script>art.dialog.opener.setImg('$url');</script>");
            }
        }
        exit;
    }


    //审核代理
    public function agent_act()
    {
        $sq_id = Filter::int(Req::args('sq_id'));
        $dl_id = Filter::int(Req::args('dl_id'));
        $dl_lx = Filter::int(Req::args('dl_lx'));

        $model = new Model('agent');
        $model->data(array('is_ok' => 2, 'sh_time' => date('Y-m-d H:i:s')))->where("user_id=$dl_id")->update();
        $model->table('sq_list')->data(array('is_ok' => 1))->where("sq_id=$sq_id")->update();
        $model->table('user')->data(array('dl_lx' => $dl_lx))->where("id=$dl_id")->update();
        //Jjjs::tjj_ckordp($dl_id,4);//计算奖金
        echo "<script>parent.close_dialog();</script>";
    }

    //申请代理查看
    public function agent_view()
    {
        $this->layout = "blank";
        $id = Filter::int(Req::args('id'));
        if ($id) {
            $model = new Model('agent as wd');
            $dp = $model->fields("wd.*,sq.*")->join("left join sq_list as sq on wd.user_id = sq.user_id")->where("sq.sq_id=$id")->find();
            $this->assign("dp", $dp);
            $this->redirect();
        }
    }

    public function withdraw_view()
    {
        $this->layout = "blank";
        $id = Filter::int(Req::args('id'));
        if ($id) {
            $model = new Model('withdraw as wd');
            $withdraw = $model->fields("wd.*,us.name as uname,cu.balance")->join("left join user as us on wd.user_id = us.id left join customer as cu on wd.user_id = cu.user_id")->where("wd.id=$id")->find();
            $this->assign("withdraw", $withdraw);
            $this->redirect();
        }
    }


    //处理提现
    public function withdraw_act()
    {
        $id = Filter::int(Req::args('id'));
        $status = intval(Req::args('status'));
        $re_note = Filter::text(Req::args('re_note'));
        $model = new Model('withdraw as wd');
        $obj = $model->fields("wd.*,cu.balance")->join("left join customer as cu on wd.user_id = cu.user_id")->where("wd.id=$id and wd.status=0")->find();
        if ($obj) {
            $model->table('withdraw')->data(array('status' => $status, 're_note' => $re_note))->where("id=$id")->update();
            if ($status == 2) {
                $model->table('customer')->data(array('balance' => "`balance`+" . $obj['sq_money']))->where('user_id=' . $obj['user_id'])->update();

                // Log::balance(0-$obj['amount'],$obj['user_id'],'提现到'.$obj['type_name'].',账号:'.$obj['account'],3,$this->manager['id']);
            }
            echo "<script>parent.close_dialog();</script>";

        }
    }

    public function export_excel()
    {
        $this->layout = '';
        $condition = Req::args("condition");
        $fields = Req::args("fields");
        $condition = Common::str2where($condition);
        $notify_model = new Model("notify as n");
        if ($condition) {
            $items = $notify_model->fields("n.*,go.name as goods_name,u.name as user_name")->join("left join user as u on n.user_id = u.id left join goods as go on n.goods_id = go.id")->where($condition)->findAll();
            if ($items) {
                header("Content-type:application/vnd.ms-excel");
                header("Content-Disposition:filename=csat.xls");
                $fields_array = array('email' => '邮件', 'mobile' => '电话', 'user_name' => '用户名', 'goods_name' => '商品名', 'register_time' => '登记时间', 'notify_status' => '是否通知');
                $str = "<table border=1><tr>";
                foreach ($fields as $value) {
                    $str .= "<th>" . iconv("UTF-8", "GB2312", $fields_array[$value]) . "</th>";
                }
                $str .= "</tr>";
                foreach ($items as $item) {
                    $str .= "<tr>";
                    foreach ($fields as $value) {
                        $str .= "<td>" . iconv("UTF-8", "GB2312", $item[$value]) . "</td>";
                    }
                    $str .= "</tr>";
                }
                $str .= "</table>";
                echo $str;
                exit;
            } else {
                $this->msg = array("warning", "没有符合该筛选条件的数据，请重新筛选！");
                $this->redirect("notify_list", false, Req::args());
            }
        } else {
            $this->msg = array("warning", "请选择筛选条件后再导出！");
            $this->redirect("notify_list", false);
        }

    }

    public function send_notify()
    {
        $condition = Req::args("condition");
        $notify_model = new Model("notify as n");
        $condition = Common::str2where($condition);
        if ($condition != null) {
            $items = $notify_model->fields("n.*,go.name as goods_name,u.name as user_name")->join("left join user as u on n.user_id = u.id left join goods as go on n.goods_id = go.id")->where($condition)->findAll();
            $mail = new Mail();
            $msg_model = new Model("msg_template");
            $template = $msg_model->where("id=1")->find();
            $success = 0;
            $fail = 0;
            foreach ($items as $item) {
                $subject = str_replace(array('{$user_name}', '{$goods_name}'), array($item['user_name'], $item['goods_name']), $template['title']);
                $body = str_replace(array('{$user_name}', '{$goods_name}'), array($item['user_name'], $item['goods_name']), $template["content"]);
                $status = $mail->send_email($item['email'], $subject, $body);
                if ($status) {
                    $data = array('notify_time' => date('Y-m-d H:i:s'), 'notify_status' => '1');
                    $notify_model->data($data)->where('id=' . $item['id'])->update();
                    $success++;
                } else {
                    $fail++;
                }
            }
            $return = array('isError' => false, 'count' => count($items), 'success' => $success, 'fail' => $fail);
        } else {
            $return = array('isError' => true, 'msg' => '没有选择筛选条件！');
        }
        echo JSON::encode($return);
    }

    public function message_send()
    {
        $condition = Req::post("condition");
        $condition = Common::str2where($condition);
        $model = new Model();
        Req::post("time", date('Y-m-d H:i:s'));
        $has_user = true;
        if ($condition != '') {
            $users = $model->table("customer")->where($condition)->find();
            if ($users) $has_user = true;
            else $has_user = false;
        }
        if ($has_user) {
            $last_id = $model->table("message")->insert();
            $model->table("customer")->data(array('message_ids' => "concat_ws (',',`message_ids`,'$last_id')"));
            if ($condition != '') $model->where($condition)->update();
            else $model->update();
            $this->redirect("message_list");
        } else {
            $this->msg = array("warning", "发送的对象不存在，因此无法发送，请修改筛选条件重新发送！");
            $this->redirect("message_edit", false, Req::args());
        }

    }

    public function message_edit()
    {
        $model = new Model('grade');
        $rows = $model->findAll();
        $grade = '';
        foreach ($rows as $row) {
            $grade .= $row['id'] . ":'" . $row['name'] . "',";
        }
        $grade = trim($grade, ',');
        $this->assign('grade', $grade);
        $this->redirect();
    }

    //留言咨询
    function ly_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    function ly_edit()
    {
        $id = intval(Req::args("id"));
        if ($id) {
            $model = new Model("ly");
            $obj = $model->where("id=$id")->find();
            if ($obj) {
                $user = $model->table("user")->fields("name")->where("id=" . $obj['user_id'])->find();
                $obj['user_name'] = isset($user['name']) ? $user['name'] : '用户已不存在';
                $this->redirect("ly_edit", false, $obj);
            } else {
                $this->msg = array("error", "此留言不存在，查证后再试！");
                $this->redirect("ly_edit", false, Req::args());
            }
        } else {
            $this->msg = array("error", "此留言不存在，查证后再试！");
            $this->redirect("ly_edit", false, Req::args());
        }
    }

    function ly_save()
    {
        $id = Req::args('id');
        $content = strval(Req::args("content"));
        $model = new Model();
        $result = $model->table("ly")->data(array('content' => $content))->where("id=$id")->update();
        if ($result) {
            $this->msg = array("success", "回复成功");
        } else {
            $this->msg = array("error", "回复失败");
        }
        $this->redirect("ly_list", false, array('msg' => $this->msg));
    }

    //对应article的验证与过滤
    function ly_validator()
    {
        $manager = $this->safebox->get('manager');
        $rules = array('content:required:内容不能为空！');
        $info = Validator::check($rules);
        if ($info == true) {
            Filter::form(array('text' => 'content'));
            $content = TString::nl2br(Req::args('content'));
            Req::args('content', $content);
            if (Req::args('id') != null) {
                Req::args('reply_time', date('Y-m-d H:i:s'));
                Req::args('status', 1);
                Req::args('admin_id', $manager['id']);
            }
        }
        return $info;
    }

    function ask_edit()
    {
        $id = intval(Req::args("id"));
        if ($id) {
            $model = new Model("ask");
            $obj = $model->where("id=$id")->find();
            if ($obj) {
                $goods = $model->table("goods")->fields("name")->where("id=" . $obj['goods_id'])->find();
                $user = $model->table("user")->fields("name")->where("id=" . $obj['user_id'])->find();
                $obj['goods_name'] = isset($goods['name']) ? $goods['name'] : '<h1 class="red">商品已经不存在</h1>';
                $obj['user_name'] = isset($user['name']) ? $user['name'] : '用户已不存在';
                $this->redirect("ask_edit", false, $obj);
            } else {
                $this->msg = array("error", "此咨询不存在，查证后再试！");
                $this->redirect("ask_edit", false, Req::args());
            }
        } else {
            $this->msg = array("error", "此咨询不存在，查证后再试！");
            $this->redirect("ask_edit", false, Req::args());
        }
    }


    //商品咨询
    function ask_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    //商品评价
    function review_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    //对应article的验证与过滤
    function ask_validator()
    {
        $manager = $this->safebox->get('manager');
        $rules = array('content:required:内容不能为空！');
        $info = Validator::check($rules);
        if ($info == true) {
            Filter::form(array('text' => 'content'));
            $content = TString::nl2br(Req::args('content'));
            Req::args('content', $content);
            if (Req::args('id') != null) {
                Req::args('reply_time', date('Y-m-d H:i:s'));
                Req::args('status', 1);
                Req::args('admin_id', $manager['id']);
            }
        }
        return $info;
    }

    function customer_list()
    {

		$condition = Req::args("condition");

		$condition_str = Common::str2where($condition);
		if($condition_str) $this->assign("where",$condition_str);
		else $this->assign("where","1=1");
		$this->assign("condition",$condition);
		$this->redirect();
	}

    function no_customer_list()
    {

        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    public function customer_edit()
    {
        $id = Req::args("id");

        $customer = Req::args();
        if ($id) {
            $model = new Model("customer as c");
            $customer = $model->join("user as u on c.user_id = u.id")->where("c.user_id=" . $id)->find();
        }
        $this->redirect('customer_edit', false, $customer);
    }

    public function customer_del()
    {
        $id = Req::args("id");
        if (is_array($id)) {
            $cond = ' in (' . implode(",", $id) . ')';
        } else {
            $cond = " = $id";
        }
        $model = new Model();
        $users = $model->table("user")->where("id $cond")->findAll();
        $model->table("customer")->where("user_id $cond")->delete();
        $model->table("user")->where("id $cond")->delete();
        if ($users) {
            $user_names = "";
            foreach ($users as $user) {
                $user_names .= $user['name'] . "、";
            }
            $user_names = trim($user_names, '、');
            Log::op($this->manager['id'], "删除会员", "管理员[" . $this->manager['name'] . "]:删除了会员 " . $user_names);
        }
        $this->redirect("customer_list");
    }

    public function customer_save()
    {
        $id = Req::args("id");
        $name = Req::args("name");
        $email = Req::args("email");
        $password = Req::args("password");
        $birthday = Req::post("birthday");
        $userModel = new Model("user");

        $customerModel = new Model("customer");
        if ($id) {
            $user = $userModel->where("id=$id")->find();
            if ($user) {
                if ($name && $email) $userModel->data(array('name' => $name, 'email' => $email))->where("id=$id")->update();
                $customerModel->where("user_id=$id")->update();
                Log::op($this->manager['id'], "修改会员", "管理员[" . $this->manager['name'] . "]:修改了会员 " . $user['name'] . " 的信息");
            }
        } else {
            $user = $userModel->where("name = '$name' or email = '$email'")->find();
            if ($user) {
                $this->msg = array("error", "用户名或邮箱已经存在！");
                $this->redirect("customer_edit", false);
                exit;
            } else {
                $validcode = CHash::random(8);
                $last_id = $userModel->data(array('name' => $name, 'password' => CHash::md5($password, $validcode), 'validcode' => $validcode, 'email' => $email))->add();
                Req::args('user_id', $last_id);
                if (!Validator::date(Req::post('birthday'))) Req::post('birthday', date('Y-m-d'));
                $customerModel->insert();
                Log::op($this->manager['id'], "添加会员", "管理员[" . $this->manager['name'] . "]:添加了会员 " . $name . " 的信息");
            }

        }
        $this->redirect("customer_list");
    }

    public function customer_password()
    {
        $id = Req::post("id");
        $password = Req::post("password");
        $passwordtwo = Req::post("passwordtwo");
        $info = array('status' => 'fail');
        if ($id && $password && $passwordtwo) {
            $model = new Model("user");
            $validcode = CHash::random(8);
            $flag = $model->where("id=$id")->data(array('pass1' => $password, 'pass2' => $passwordtwo, 'password' => CHash::md5($password, $validcode), 'passwordtwo' => CHash::md5($passwordtwo), 'validcode' => $validcode))->update();
            if ($flag) $info = array('status' => 'success');
        }
        echo JSON::encode($info);
    }


    public function is_tuijian()
    {
        $id = Req::args('id');
        $model = new Model();
        $dp_obj = $model->table("dp")->where("user_id=$id")->find();
        if (intval($dp_obj['is_tuijian']) === 0) {
            $data = array('is_tuijian' => 1);
        } else {
            $data = array('is_tuijian' => 0);
        }
        $result = $model->table("dp")->data($data)->where("user_id=$id")->update();
        if ($result) {
            $this->msg = array("success", "操作成功");
        } else {
            $this->msg = array("error", "操作失败");
        }
        $url = Url::getRefRoute();
        $this->redirect($url, true, array('msg' => $this->msg));


    }

    public function get_user_id_by_buy_or_sell()
    {
        $username = Filter::text(trim(Req::args("username")));
        $model = new Model();
        $userObj = $model->table("user")->where("name='{$username}'")->find();
        if (empty($userObj)) {
            echo '0';
        } else {
            echo $userObj['id'];
        }

    }

    function buy_sell_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        /*
        $model = new Model();
        $sql = "select u.name as buy_name,t.*,(select name from zyk_user where id=t.seller_id) as sell_name from zyk_transaction_buy as t left join zyk_user as u on t.user_id=u.id;";
        $list = $model->query($sql);
        $this->assign("list", $list);
        */
        $this->redirect();
    }

    function exchange_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    function jjmx_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }

    function zz_list()
    {
        $condition = Req::args("condition");
        $condition_str = Common::str2where($condition);
        if ($condition_str) $this->assign("where", $condition_str);
        else $this->assign("where", "1=1");
        $this->assign("condition", $condition);
        $this->redirect();
    }


    function download_widthdraw_execl_file()
    {
        Common::download_widthdraw_execl_file();
    }

    function download_recharge_execl_file()
    {
        Common::download_recharge_execl_file();
    }

    //select user_id,sum(sq_money) as sql_money,sum(txf) as txf,sum(amount) as amount from zyk_withdraw where status=1 group by user_id;


    public function withdraw_user_list()
    {


        $model = new Model();
        $username = Filter::text(Req::args('username'));
        if (!empty($username)) {
            $this->assign("username", $username);
            $uobj = Common::get_user_obj_by_name($username);
            $uid = $uobj['id'];
            $sql = "select user_id,sum(sq_money) as total_sq_money,sum(txf) as total_txf,sum(amount) as total_amount from zyk_withdraw where status=1 and user_id=$uid group by user_id order by sum(sq_money) desc";
        } else {
            $sql = "select user_id,sum(sq_money) as total_sq_money,sum(txf) as total_txf,sum(amount) as total_amount from zyk_withdraw where status=1 group by user_id order by sum(sq_money) desc";
        }

        $user_list = $model->query($sql);

        foreach ($user_list as $k => $v) {
            $user_id = $v['user_id'];
            $user_obj = Common::get_user_obj($user_id);
            $user_list[$k]['uname'] = $user_obj['name'];
        }
        $this->assign("user_list", $user_list);
        $this->redirect();
    }


    public function up_down_list()
    {
        $this->layout = "blank";
        $id = Filter::int(Req::args('id'));
        if ($id) {
            $model = new Model();
            $customer = $model->table("customer")->where("user_id =" . $id)->find();
            $this->assign("group_id", $customer['group_id']);
//			if (!empty($customer['dl_area'])) {
//				$arr = explode(',',$customer['dl_area']);
//				$this->assign("province",$arr[0]);
//				$this->assign("city",$arr[1]);
//				$this->assign("county",$arr[2]);
            $this->assign('id', $id);
//			}

            $this->redirect();
        }
    }

    public function up_down_list_fh()
    {
        $this->layout = "blank";
        $id = Filter::int(Req::args('id'));
        if ($id) {
            $model = new Model();
            $customer = $model->table("customer")->where("user_id =" . $id)->find();
            $this->assign("vip_id", $customer['vip_id']);
            $this->assign("customer", $customer);
            $this->assign('id', $id);
//			}

            $this->redirect();
        }
    }

    /**
     *  会员升降级
     */
    public function up_down_active()
    {
        $id = Req::post('id');
        $agent = Req::post('agent');//升级等级
        $province = Req::post('province');//省
        $city = Req::post('city');  //市
        $county = Req::post('county'); //县

        if (empty($agent)) {
            $info = array('status' => 'error', 'msg' => '级别不能为空!');
            echo json_encode($info);
            die;
        }

        //判断区域是否为空
        if (empty($province) || empty($city) || empty($county)) {
            $info = array('status' => 'error', 'msg' => '省市县必须选择!');
            echo json_encode($info);
            die;
        }

        $user_obj = Common::get_user_obj($id);//要升级的用户

        $dl_area = $province . ',' . $city . ',' . $county; //代理区域
        if (Common::check_area_exist($agent, $dl_area)) {
            $info = array('status' => 'error', 'msg' => '该区域已经被占领,请选择其他区域!');
            echo json_encode($info);
            die;
        }


        $model = new Model();
        $result = $model->table('customer')->where('user_id=' . $user_obj['id'])->data(array('group_id' => $agent, 'dl_area' => $dl_area))->update();
        if ($result) {
            if ($user_obj['group_id'] > $agent) {

                Log::op($this->manager['id'],"降级了用户投资级别","管理员[".$this->manager['name']."]:把用户
                          [".$user_obj['name']."]从".Common::get_agent_name($user_obj['group_id'])."、代理区域为".Common::get_dl_area_name($user_obj['dl_area']).
                    ",降级为".Common::get_agent_name($agent)."、代理区域为".Common::get_dl_area_name($dl_area));

                $info = array('status' => 'success', 'msg' => '降级成功!');
                echo json_encode($info);
                die;
            } else if ($user_obj['group_id'] = $agent) {

                Log::op($this->manager['id'],"更改了用户投资级别","管理员[".$this->manager['name']."]:把用户
                          [".$user_obj['name']."]从".Common::get_agent_name($user_obj['group_id'])."、代理区域为".Common::get_dl_area_name($user_obj['dl_area']).
                    ",更改为".Common::get_agent_name($agent)."、代理区域为".Common::get_dl_area_name($dl_area));

                $info = array('status' => 'success', 'msg' => '操作成功!');
                echo json_encode($info);
                die;
            } else if ($user_obj['group_id'] < $agent) {

                Log::op($this->manager['id'],"升级了用户投资级别","管理员[".$this->manager['name']."]:把用户
                          [".$user_obj['name']."]从".Common::get_agent_name($user_obj['group_id'])."、代理区域为".Common::get_dl_area_name($user_obj['dl_area']).
                    ",升级为".Common::get_agent_name($agent)."、代理区域为".Common::get_dl_area_name($dl_area));

                $info = array('status' => 'success', 'msg' => '升级成功!');
                echo json_encode($info);
                die;
            }
        }

        $info = array('status' => 'error', 'msg' => '操作失败!');
        echo json_encode($info);
        die;

    }

    /**
     *  分红升降级
     */
    public function up_down_active_fh()
    {
        $id = Req::post('id');
        $agent = Req::post('agent');//升级等级
        if (empty($agent)) {
            $info = array('status' => 'error', 'msg' => '级别不能为空!');
            echo json_encode($info);
            die;
        }

        $user_obj = Common::get_user_obj($id);//要升级的用户

        if($user_obj['vip_id'] == $agent){
            Log::op($this->manager['id'],"改变了用户分红级别","管理员[".$this->manager['name']."]:把用户
                          [".$user_obj['name']."]从".Common::get_agent_name($user_obj['vip_id']).
                ",改变为".Common::get_agent_name($agent));

            $info = array('status' => 'success', 'msg' => '操作成功!');
            echo json_encode($info);
            die;
        }

        $model = new Model();
        $result = $model->table('customer')->where('user_id=' . $user_obj['id'])->data(array('vip_id' => $agent))->update();
        if ($result) {
            if ($user_obj['vip_id'] > $agent) {

                Log::op($this->manager['id'],"降级了用户分红级别","管理员[".$this->manager['name']."]:把用户
                          [".$user_obj['name']."]从".Common::get_agent_name($user_obj['vip_id']).
                    ",降级为".Common::get_agent_name($agent));

                $info = array('status' => 'success', 'msg' => '降级成功!');
                echo json_encode($info);
                die;
            } else if ($user_obj['vip_id'] < $agent) {

                Log::op($this->manager['id'],"升级了用户分红级别","管理员[".$this->manager['name']."]:把用户
                          [".$user_obj['name']."]从".Common::get_agent_name($user_obj['vip_id']).
                    ",升级为".Common::get_agent_name($agent));

                $info = array('status' => 'success', 'msg' => '升级成功!');
                echo json_encode($info);
                die;
            }else if ($user_obj['vip_id'] = $agent){

            }
        }

        $info = array('status' => 'error', 'msg' => '操作失败!');
        echo json_encode($info);
        die;

    }


    /**
     * 区域
     */
    public function transform()
    {
        $id = Req::args("id");
        $model = new Model();
        $arr_city = $model->table("area")->where("parent_id = " . $id)->findAll();
        $str = '';
        for ($i = 0; $i < count($arr_city); $i++) {
            $id = $arr_city[$i]['id'];
            $str .= "<option value='{$id}'>{$arr_city[$i]['name']}</option>";
        }

        echo $str;

    }

    /**
     * 是否允许提现
     */
    public function ok_withdraw ()
    {

        $id = Req::args("id");
        $model = new Model("user");
        $lock = $model->where("id=" . $id)->find()['lock'];
        if ($lock == 1) {
            $zt = 0;
        } else {
            $zt = 1;
        }
        $model->data(array('lock' => $zt))->where("id=" . $id)->update();
        $this->redirect("customer_list");
    }

}
